/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package converters;

import be.Maquina;
import beans.ManagedBeanMaquina;
import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author argos
 */
@FacesConverter(value = "maquinaConverter")
public class MaquinaConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {

        if (context == null) {
            throw new NullPointerException("context");
        }
        if (component == null) {
            throw new NullPointerException("component");
        }
        FacesContext ctx = FacesContext.getCurrentInstance();
        ValueExpression vex = ctx.getApplication().getExpressionFactory().createValueExpression(ctx.getELContext(), "#{managedBeanMaquina}", ManagedBeanMaquina.class);
        ManagedBeanMaquina managedBean = (ManagedBeanMaquina) vex.getValue(ctx.getELContext());
        Maquina objeto;
        try {
            // System.out.println(" tamaño " +managedBean.getMyMapItems().size());
            if (managedBean.getMyMapItems().size() < 1) {
                // No se han llenado los Objetos
                // System.out.println(" Mandamos a Llenar los My");
                managedBean.llenar_my();
            }
            objeto = managedBean.getObjeto(new Integer(value));
            //System.out.println(" Objeto " +objeto.getNombre());
        } catch (NumberFormatException e) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Valor Desconocido", "Este no es un Numero valido");
            throw new ConverterException(message);
        }
        if (objeto == null) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Valor Desconocido", "Objeto Desconocio");
            throw new ConverterException(message);
        }
        return objeto;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {

        if (context == null) {
            throw new NullPointerException("context");
        }
        if (component == null) {
            throw new NullPointerException("component");
        }
        if (value == null || ((Maquina) value).getId() == null) {
            return "";
        }

        return ((Maquina) value).getId().toString();
    }
}
